package net.dntuan.training.mvc.controller;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.WebAttributes;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author tuan.dangnhu
 * 
 *         $LastChangedRevision: 88 $ $LastChangedDate: 2014-04-25 17:48:50 +0000 (Fri, 25 Apr 2014) $
 */
@Controller
public class LoginController {
    private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);

    @Value("#{props.key1}")
    private String foo;

    @RequestMapping(value = "login")
    public String getLoginPage() {
        LOGGER.debug("welcome to The login page!");
        LOGGER.debug("value for 'key1' from properties file: " + foo);
        return "login";
    }

    @RequestMapping(value = "login", params = "error")
    public String loginFailure(Model model, HttpSession session) {
        // show messages on login form if authentication failed
        Object obj = session.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
        if (obj instanceof AuthenticationException) {
            LOGGER.debug(obj.getClass().getName());
            AuthenticationException authException = (AuthenticationException) obj;
            LOGGER.debug(authException.getMessage());
            model.addAttribute("message", new String(authException.getMessage()));
            session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
        }
        return "login";
    }

    @RequestMapping(value = "welcome")
    public String getWelcomePage(Model model) {
        Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (obj != null && obj instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) obj;
            model.addAttribute("username", userDetails.getUsername());
            model.addAttribute("roles", userDetails.getAuthorities());
        }
        return "welcome";
    }
}
